package com.ygxsk.carhome.ui.auth;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.PopTip;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.AuthManageType;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.event.EventAuthDetail;
import com.ygxsk.carhome.event.EventAuthMain;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.ButtonAutoCancelListener;
import com.ygxsk.carhome.listener.Delivery;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.response.AttestationResultVo;
import com.ygxsk.carhome.response.CarAttestation;
import com.ygxsk.carhome.response.CarAttestationVo;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.sys.PermissionInterceptor;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.AuthManageDetailAdapter;
import com.ygxsk.carhome.utils.CommTools;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.StringCodeUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-24  14:40
 * @Description:认证的详情内容；
 *
 * 1：
已认证 在认证详情内--不能有【取消】按钮
2：其余情况：待联系 待认证 ，【取消】按钮都在；
3：已认证---已联系--按钮不能在；
 *
 */
public class AuthManageDetailActivity extends ErrorActivity implements ErrorParentExtraSingle, EasyPermissions.PermissionCallbacks {


    //包裹底部三个按钮的外侧布局，而且是在【已取消】状态下，三个按钮都不能展示的
    @BindView(R.id.linearlayoutroundtextviewdetailoutside)
    RelativeLayout linearLayoutRoundTextViewDetail;

    //添加认证按钮
    @BindView(R.id.roundtextviewaddauthsystemdetail)
    RoundTextView roundTextViewAddAuthSystemDetail;

    //取消按钮
    @BindView(R.id.roundtextviewauthcanceldetail)
    RoundTextView roundTextViewAuthCancelDetail;

    //已联系 按钮
    @BindView(R.id.roundtextviewauthhascontacted)
    RoundTextView roundTextViewAuthHasContacted;

    //下拉刷新 详情
    @BindView(R.id.refreshlayoutauthmanagedetail)
    SmartRefreshLayout refreshLayoutAuthManageDetail;

    @BindView(R.id.recyclerviewinauthmanagedetail)
    RecyclerView recyclerViewInAuthManageDetail;

    //该页面仅仅只有预览的能力
    private static final int PRC_PHOTO_PREVIEW = 1;

    //潜在客户，
    private ArrayList<AttestationResultVo> mDataResources = new ArrayList<>();

    //外侧拨打电话的能力
    private String listItem_call_phone;

    //筛选条件的 汽车的类型；
//    private ArrayList<NomalCustomBean> dataListCarType = new ArrayList<>();
//    //客户的来源
//    private ArrayList<NomalCustomBean> dataListFromWhere = new ArrayList<>();
//    //该客户的分配状态
//    private ArrayList<NomalCustomBean> dataListStateItem = new ArrayList<>();

    //认证人  姓名
    private TextView textViewPersonName;
    //认证的状态
    private TextView textViewAuthStatus;
    private TextView textViewAuthPersonPhone;
    //认证人 手机号
    //认证时间
    private TextView textViewAuthPersonTime;
    //认证车辆的 车辆信息
    private TextView textViewAuthCarCurrent;
    //认证体系
    private TextView textViewCarSystemInDetailValue;

    //一个适配器
    private AuthManageDetailAdapter authManageDetailAdapter;
    //取消原因的 弹窗布局
    private BasePopupView basePopupView_cancelReason;

    //从列表携带 认证这条数据；
    private CarAttestation extra_carattestation;

    private BGANinePhotoLayout mCurrentClickNpl;

    //确认的弹窗，因为底部有一个弹窗，不用这个弹窗会造成确认按钮无法点击
    private BasePopupView popupViewConfirm;

    //给列表九宫格查看准备
    private BGANinePhotoLayout.Delegate bgaNinePhotoLayoutDelegate = new BGANinePhotoLayout.Delegate() {
        @Override
        public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
            //点击九宫格,查看大图
            mCurrentClickNpl = ninePhotoLayout;

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                photoPreviewWrapper();

            } else {

                photoPreviewIntentXXPermissions();

            }
        }

        @Override
        public void onClickExpand(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
            //点击展开的
            ninePhotoLayout.setIsExpand(true);
            ninePhotoLayout.flushItems();
        }
    };

    /**
     * 图片预览，兼容6.0动态权限
     */
    @AfterPermissionGranted(PRC_PHOTO_PREVIEW)
    private void photoPreviewWrapper() {
        if (mCurrentClickNpl == null) {
            return;
        }

        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

        if (EasyPermissions.hasPermissions(this, perms)) {

            CommTools.photoPreviewIntent(mActivityInstance, mActivityInstance, mCurrentClickNpl);

        } else {

            //EasyPermissions.requestPermissions(this, "图片预览需要以下权限:\n\n1.访问设备上的照片", PRC_PHOTO_PREVIEW, perms);
            EasyPermissions.requestPermissions(this, StringUtils.getString(R.string.imagenicelook), PRC_PHOTO_PREVIEW, perms);

        }

    }


    private void photoPreviewIntentXXPermissions() {

        if (!XXPermissions.isGranted(AuthManageDetailActivity.this, com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {

            //因为有存储图片的需要，所以也申请一下权限
            CommUtils.checkMaterialDialog(materialDialog);
            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_ALBUM, new AuthorityCallbackListener() {
                @Override
                public void doSomeThing() {

                    CommUtils.checkMaterialDialog(materialDialog);

                    XXPermissions.with(AuthManageDetailActivity.this)
                            // 适配分区存储应该这样写
                            //.permission(Permission.Group.STORAGE)
                            // 不适配分区存储应该这样写
//                    .permission(com.hjq.permissions.Permission.CAMERA)//
                            .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
//                  .permission(com.hjq.permissions.Permission.READ_MEDIA_VIDEO)//
//                  .permission(com.hjq.permissions.Permission.READ_MEDIA_AUDIO)//
                            //).permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE
                            .interceptor(new PermissionInterceptor())
                            .request(new OnPermissionCallback() {

                                @Override
                                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                    if (!allGranted) {
                                        return;
                                    }

                                    Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                            PermissionNameConvert.getPermissionString(AuthManageDetailActivity.this, permissions)));

                                    CommTools.photoPreviewIntent(mActivityInstance, mActivityInstance, mCurrentClickNpl);

                                }
                            });
                }
            });

        } else {

            CommTools.photoPreviewIntent(mActivityInstance, mActivityInstance, mCurrentClickNpl);

        }

    }

//    private void photoPreviewIntent() {
//
////            File downloadDir = new File(Environment.getExternalStorageDirectory(), ConstantSign.BGAPHOTOPICKERDOWNLOAD);
//        File downloadDir = new File(PathUtils.getExternalAppFilesPath(), ConstantSign.BGAPHOTOPICKERDOWNLOAD);
//        BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder = new BGAPhotoPreviewActivity.IntentBuilder(this);
//        if (true) {
//            // 保存图片的目录，如果传 null，则没有保存图片功能
//            photoPreviewIntentBuilder.saveImgDir(downloadDir);
//        }
//
//        if (mCurrentClickNpl.getItemCount() == 1) {
//            // 预览单张图片
//            photoPreviewIntentBuilder.previewPhoto(mCurrentClickNpl.getCurrentClickItem());
//
//        } else if (mCurrentClickNpl.getItemCount() > 1) {
//            // 预览多张图片
//            photoPreviewIntentBuilder.previewPhotos(mCurrentClickNpl.getData())
//                    .currentPosition(mCurrentClickNpl.getCurrentClickItemPosition()); // 当前预览图片的索引
//        }
//
//        startActivity(photoPreviewIntentBuilder.build());
//
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == PRC_PHOTO_PREVIEW) {
            //Toast.makeText(this, "您拒绝了「图片预览」所需要的相关权限!", Toast.LENGTH_SHORT).show();
            Toast.makeText(this, StringUtils.getString(R.string.image_preview), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initloading();

        initViews();

        gainDatas();

        //有刷新监听的例如【取消认证】刷新它自己；
        //列表之内需要向外部广播数据
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
//                .keyboardEnable(true)
                .init();

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_auth_manage_detail;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        //这个可能是动态的，不同身份 是不同标题：服务站经理存款业绩排名
        toolbarHelper.setTitle(getString(R.string.title_auth_manage_detail));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        toolbarHelper.setLayoutRight(false, 0, "", null);

//        toolbarHelper.setLayoutRight(true, 1, "添加", new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//                //历史记录的页面布局
//                Bundle extra_bundle = new Bundle();
//                //这里空携带
//                ActivityUtils.startActivity(extra_bundle, RunManOpenCardEditActivity.class);
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        //页面上都是选择弹窗的；
        //布局的适配器填充，下拉刷新等等；
        recyclerViewInAuthManageDetail.setLayoutManager(new MyLinearLayoutManager(this));
        authManageDetailAdapter = new AuthManageDetailAdapter(R.layout.authmanagedetailadapter, mDataResources);
        if (bgaNinePhotoLayoutDelegate != null) {
            authManageDetailAdapter.setBgaNinePhotoLayoutDelegate(bgaNinePhotoLayoutDelegate);
        }
        recyclerViewInAuthManageDetail.setAdapter(authManageDetailAdapter);

        //字段内容是 顶部的header内容
        authManageDetailAdapter.removeAllHeaderView();
        authManageDetailAdapter.addHeaderView(getHeaderView(recyclerViewInAuthManageDetail));

        authManageDetailAdapter.notifyDataSetChanged();

        authManageDetailAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                // : 2023-07-13 15:07 跳转到这个客户的详情页面
//                Bundle extra_bundle = new Bundle();
//                extra_bundle.putParcelable(ExtraKey.EXTRA_RUNMANGROUPMANAGEBEAN, runManGroupManageBeanItem);
//                ActivityUtils.startActivity(extra_bundle, LeadDetailActivity.class);

            }
        });

        refreshLayoutAuthManageDetail.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        getServerDatas();
                        refreshLayout.finishRefresh();
                    }
                });


            }
        });


        //两个按钮的点击能力；
        //【添加认证】
        if (roundTextViewAddAuthSystemDetail != null) {

            roundTextViewAddAuthSystemDetail.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {

                    Bundle extra_bundle = new Bundle();
//
//                    //String shopId = assetInSideBean.getShopId();
//
//                    //是添加进来的
//                    extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE,ExtraValue.VALUE_JUMP_FORM_ASSET_ADD);
//
//                    extra_bundle.putString(ExtraKey.EXTRA_ASSETINSIDEBEAN_SHOPID,assetInSideBean.getShopId());
//
//                    //携带这条数据的 本身 id 过去
                    extra_bundle.putParcelable(ExtraKey.EXTRA_CARATTESTATION, extra_carattestation);
//                    //
//                    extra_bundle.putParcelableArrayList(ExtraKey.EXTRA_ASSETUNDERBUSINESSINFOLISTOUTSIDE, assetUnderBusinessInfoListOutSide);
//
                    ActivityUtils.startActivity(extra_bundle, AuthAddSubmitActivity.class);

                }
            });

        }

        //【已联系】
        if (roundTextViewAuthHasContacted != null) {

            roundTextViewAuthHasContacted.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {

                    CommUtils.checkDialog(mAlertView);
                    mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                            StringUtils.getString(R.string.submit_sure_message),//提示内容：已确定和客户取得联系
                            StringUtils.getString(R.string.clearcachecancel), //取消
                            new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                            null, mActivityInstance, AlertView.Style.Alert, new com.ygxsk.carhome.alertview.OnItemClickListener() {//
                        @Override
                        public void onItemClick(Object o, int position) {

                            if (position != AlertView.CANCELPOSITION) {

                                method_authHasContacted_upLoad();

                            }
                        }
                    });

                    mAlertView.setCancelable(true);
                    mAlertView.show();

                }
            });
        }

        //【取消认证】
        if (roundTextViewAuthCancelDetail != null) {

            roundTextViewAuthCancelDetail.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {
                    //取消 弹窗等，输入 取消弹窗
                    //直接弹窗：
                    basePopupView_cancelReason = new XPopup.Builder(AuthManageDetailActivity.this)
                            .hasShadowBg(true)
                            //.moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面;
                            .isViewMode(true)
                            .autoFocusEditText(true)//
                            .autoOpenSoftInput(true)//
                            .asCustom(new AuthCancelEditReasonPopu(AuthManageDetailActivity.this,//
                                    ExtraValue.VALUE_JUMP_FORM_AUTH_DETAIL_CANCEL_REASON, new ButtonAutoCancelListener() {

                                @Override
                                public void buttonAuthCancel() {

                                    if (basePopupView_cancelReason != null) {
                                        basePopupView_cancelReason.dismiss();
                                    }

                                }

                                @Override
                                public void buttonAuthSure(String cancelReason) {

                                    //取消接口
                                    //校验取消的原因：
                                    if (TextUtils.isEmpty(cancelReason)) {//服务站运营经理的初始值-1说明没有赋值，提交不过去
//                                        CommUtils.checkDialog(mAlertView);
//                                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.check_auth_cancel_reason_upload), true);
//                                        mAlertView.show();
                                        PopTip.show(StringUtils.getString(R.string.check_auth_cancel_reason_upload)).iconError();

                                        return;
                                    }

                                    popupViewConfirm = new XPopup.Builder(AuthManageDetailActivity.this)
                                            .isDestroyOnDismiss(true)
                                            .asConfirm(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //标题
                                                    StringUtils.getString(R.string.submit_repair_cancel_message),//文本内容:确定取消吗？
                                                    StringUtils.getString(R.string.clearcachecancel), //取消按钮
                                                    StringUtils.getString(R.string.clearcachetitlesure),//确定按钮
                                                    new OnConfirmListener() {
                                                        @Override
                                                        public void onConfirm() {

                                                            method_authCancel_upLoad(cancelReason);

                                                        }
                                                    }, null, false);

                                    popupViewConfirm.show();

//                                    CommUtils.checkDialog(mAlertView);
//                                    mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
//                                            StringUtils.getString(R.string.submit_sure_message),//提示内容：已确定和客户取得联系
//                                            StringUtils.getString(R.string.clearcachecancel), //取消
//                                            new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
//                                            null, mActivityInstance, AlertView.Style.Alert, new com.ygxsk.carhome.alertview.OnItemClickListener() {//
//                                        @Override
//                                        public void onItemClick(Object o, int position) {
//
//                                            if (position != AlertView.CANCELPOSITION) {
//
//                                                method_authCancel_upLoad(cancelReason);
//
//                                            }
//                                        }
//                                    });
//
//                                    mAlertView.setCancelable(true);
//                                    mAlertView.show();

                                }


                            }))//
                            .show();

                }
            });

        }

    }


    private View getHeaderView(RecyclerView _recyclerViewWork) {

        View assetManageHeader;

        //2021年12月28日14:54:12 发现是崩溃的日志内容：
        // java.lang.NullPointerException: Attempt to invoke virtual method
        // 'android.view.ViewParent androidx.recyclerview.widget.RecyclerView.getParent()' on a null object reference

        if ((_recyclerViewWork != null) && (_recyclerViewWork.getParent() != null)) {
            assetManageHeader = LayoutInflater.from(Utils.getApp()).inflate(//
                    R.layout.authmanageaddheader, //
                    (ViewGroup) _recyclerViewWork.getParent(),//
                    false);//
        } else {
            assetManageHeader = LayoutInflater.from(Utils.getApp()).inflate(R.layout.authmanageaddheader, null);
        }

        //添加布局内容；
        //认证人  姓名
        textViewPersonName = (TextView) assetManageHeader.findViewById(R.id.textviewpersonname);
        textViewAuthStatus = (TextView) assetManageHeader.findViewById(R.id.textviewauthstatus);

        RelativeLayout linelayoutCallPhoneOutSide = (RelativeLayout) assetManageHeader.findViewById(R.id.linelayoutcallphoneoutside);

        //认证人 手机号
        textViewAuthPersonPhone = (TextView) assetManageHeader.findViewById(R.id.textviewauthpersonphone);
        // 认证时间
        textViewAuthPersonTime = (TextView) assetManageHeader.findViewById(R.id.textviewauthpersontime);
        //认证车辆的 车辆信息
        textViewAuthCarCurrent = (TextView) assetManageHeader.findViewById(R.id.textviewauthcarcurrent);
        //认证体系
        textViewCarSystemInDetailValue = (TextView) assetManageHeader.findViewById(R.id.textviewcarsystemindetailvalue);

        //filldatas
        if (linelayoutCallPhoneOutSide != null) {
            linelayoutCallPhoneOutSide.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {
                    clickButton_toCallPhone(mActivityInstance, listItem_call_phone, CallHistoryBusinessType.BUSINESSTYPE_5.getIndex());
                }
            });
        }

        return assetManageHeader;

    }

    private void methodHandlerHeaderAndFooter(CarAttestationVo _carAttestationVo) {


        //                1：
//                已认证， 已取消 不能有[取消按钮和添加认证按钮];
//                在认证详情内--不能有【取消】按钮
//                2：其余情况：待联系 待认证 ，【取消】按钮都在；
//                3：已认证---已联系--【取消按钮】不能在；

        //处理三个按钮的显示和隐藏：
//                AuthManageType
//                        AUTH_TO_BE_CONTACTED(0, "待联系"), //待联系
//                        AUTH_TO_BE_CERTIFIED(1, "待认证"),//待认证
//                        AUTH_HAS_CERTIFIED(2, "已认证"),//已认证
//                        AUTH_HAS_CANCEL(3, "已取消");//已取消

        //特别注意：点了【已联系】之后，才变成【待认证】状态；这时候【已联系】按钮就不能有了；

        int status = (_carAttestationVo.getStatus());
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "status=" + status);

        Delivery.getInstance().post(new Runnable() {
            @Override
            public void run() {

                //认证人  姓名
                CommUtils.setText(textViewPersonName, _carAttestationVo.getCustomerName());
                //认证人 手机号
                CommUtils.setText(textViewAuthPersonPhone, StringCodeUtils.mobileEncrypt(_carAttestationVo.getCustomerPhone()));
                //认证状态的 汉字形式
                CommUtils.setText(textViewAuthStatus, _carAttestationVo.getStatusName());
                //认证时间
                CommUtils.setText(textViewAuthPersonTime, _carAttestationVo.getCreateTime());
                //认证车辆的 车辆信息+是个三段添加的
                String carBrandName = _carAttestationVo.getCarBrandName();
                //车系
                String carSeriesName = _carAttestationVo.getCarSeriesName();
                //车型 车辆型号
                String carModel = _carAttestationVo.getCarModel();
                //三段拼接：
                CommUtils.setText(textViewAuthCarCurrent, carBrandName + StringUtils.getString(R.string.kongge0) + carSeriesName + StringUtils.getString(R.string.kongge0) + carModel);
                //认证体系
                CommUtils.setText(textViewCarSystemInDetailValue, _carAttestationVo.getAttestationNames());

                //如果是从  正常  的 管理列表进来的，要判断；如果是 历史记录 过来的，

                if (status == (AuthManageType.AUTH_TO_BE_CONTACTED.getIndex())) {

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + AuthManageType.AUTH_TO_BE_CONTACTED.getValue());

                    //待联系--显示【取消】+【已联系】，【添加认证】隐藏
                    CommUtils.setViewVisible(linearLayoutRoundTextViewDetail);
                    CommUtils.setViewVisible(roundTextViewAuthCancelDetail);
                    CommUtils.setViewVisible(roundTextViewAuthHasContacted);
                    CommUtils.setViewGone(roundTextViewAddAuthSystemDetail);

                } else if (status == (AuthManageType.AUTH_TO_BE_CERTIFIED.getIndex())) {

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + AuthManageType.AUTH_TO_BE_CERTIFIED.getValue());

                    //待认证--显示【取消】，【已联系】隐藏，【添加认证】隐藏， 待认证 情况下，可以取消；
                    CommUtils.setViewVisible(linearLayoutRoundTextViewDetail);
                    CommUtils.setViewVisible(roundTextViewAuthCancelDetail);
                    CommUtils.setViewGone(roundTextViewAuthHasContacted);
                    // TODO: 2023-08-16 21:46 这里有疑问：有一个待认证-还让不让再次添加另一个认证，还是认证一个以后再次添加下一个？？
                    CommUtils.setViewVisible(roundTextViewAddAuthSystemDetail);

                } else if (status == (AuthManageType.AUTH_HAS_CERTIFIED.getIndex())) {//已认证：是历史记录的，还是 可以再次添加的

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + AuthManageType.AUTH_HAS_CERTIFIED.getValue());

                    //已认证--隐藏【取消】，隐藏【已联系】，【添加认证】展示
                    CommUtils.setViewVisible(linearLayoutRoundTextViewDetail);
                    CommUtils.setViewGone(roundTextViewAuthCancelDetail);
                    CommUtils.setViewGone(roundTextViewAuthHasContacted);
                    CommUtils.setViewVisible(roundTextViewAddAuthSystemDetail);

                } else if (status == (AuthManageType.AUTH_HAS_CANCEL.getIndex())) {

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + AuthManageType.AUTH_HAS_CANCEL.getValue());

                    //已取消--隐藏【取消】+【已联系】，【添加认证】也不显示，是已取消的，什么都不能操作了
                    //整个布局 都隐藏
                    CommUtils.setViewGone(linearLayoutRoundTextViewDetail);
                    CommUtils.setViewGone(roundTextViewAuthCancelDetail);
                    CommUtils.setViewGone(roundTextViewAuthHasContacted);
                    CommUtils.setViewGone(roundTextViewAddAuthSystemDetail);

                } else {

                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "没有走到逻辑");

                }

            }
        });

    }

    //直接拨打电话的能力
//    private void clickButton_toCallPhone(Activity _activity, String mPhoneNumber) {
//
//        CommUtils.checkDialog(mAlertView);
//
//        //二次确认弹窗提示
//        mAlertView = new AlertView(ConstantSign.ALERTVIEW_TITLE_FOR_PHONE,//
//                mPhoneNumber, //
//                ConstantSign.ALERTVIEW_LEFT_CANCEL,//
//                new String[]{ConstantSign.ALERTVIEW_RIGHT_COPY_INFORMATION}, //
//                null, //
//                _activity, //
//                AlertView.Style.Alert,//
//                new com.ygxsk.carhome.alertview.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(Object o, int position) {
//
//                        if (position != AlertView.CANCELPOSITION) {
//
//                            if (!TextUtils.isEmpty(mPhoneNumber)) {
//                                _activity.startActivity(CommUtils.callThePhoneNumAction_dial(mPhoneNumber));
//                            } else {
//                                ToastUtils.showShort(R.string.hasfailgetphonenumber);
//                            }
//
//                        }
//                    }
//                }
//        );
//
//        mAlertView.setCancelable(true).show();
//
//    }

    @Override
    protected void gainDatas() {

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (authManageDetailAdapter != null) {
            authManageDetailAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            getServerDatas();

        } else {
            netWorkError();
//            setEnableLoadmore(refreshLayoutAuthManageDetail, false);
        }

    }


    //获取认证详情接口
    private void getServerDatas() {


        String carAttestationId = "";
        if (extra_carattestation != null) {
            carAttestationId = extra_carattestation.getCarAttestationId();
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//
        map.put(Parameterkey.key, extra_carattestation.getCarAttestationId());//

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETDETAILBYID_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getDetailByIdForAuth_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
//                .getdetailById(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
//                        MediaType.parse(ApiService.HEADER_JSON)))
                .getDetailByIdForAuth(carAttestationId)
                .compose(AuthManageDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CarAttestationVo>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        methodNotSuccessData(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        loadingGone();

//                        if (refreshLayoutAuthManageDetail != null) {
//                            refreshLayoutAuthManageDetail.setEnableLoadMore(true);
//                        }

                    }
                }).subscribe(new Consumer<CarAttestationVo>() {
                    @Override
                    public void accept(CarAttestationVo carAttestationVo) throws Throwable {

                        if (carAttestationVo != null) {

                            listItem_call_phone = carAttestationVo.getCustomerPhone();

                            ArrayList<AttestationResultVo> attestationResultVos = (ArrayList<AttestationResultVo>) carAttestationVo.getAttestationResultVoList();

                            if (attestationResultVos != null && !attestationResultVos.isEmpty()) {
                                if (mDataResources != null) {
                                    mDataResources.addAll(attestationResultVos);
                                }
                            }

                            //填充顶部的内容
                            methodHandlerHeaderAndFooter(carAttestationVo);


                        }

                        //不能遮盖，因为有addheader，给header遮盖住了
//                        if (mDataResources != null && mDataResources.isEmpty()) {

                        //同时禁用加载更多；
//                            if (refreshLayoutAuthManageDetail != null) {
//                                refreshLayoutAuthManageDetail.setEnableLoadMore(false);
//                            }
//                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
//                        }

                        if (authManageDetailAdapter != null) {
                            authManageDetailAdapter.notifyDataSetChanged();
                        }


                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；

                    }
                });

    }

    //取消认证接口
    private void method_authCancel_upLoad(String _cancelReason) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.carAttestationId, extra_carattestation.getCarAttestationId());//认证表主键Id
        map.put(Parameterkey.reason, _cancelReason);//原因

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATECANCEL_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateCancel_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateCancel(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(AuthManageDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        //给个报错提示
                        if (!TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        if (basePopupView_cancelReason != null) {
                            basePopupView_cancelReason.dismiss();
                            basePopupView_cancelReason.onDestroy();
                            basePopupView_cancelReason = null;
                        }

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);
                        //先通知详情刷新，再通知外侧上层列表刷新
                        EventAuthDetail eventAuthDetail = new EventAuthDetail();
                        eventAuthDetail.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_AUTH_DETAIL);
                        EventBus.getDefault().post(eventAuthDetail);

                        methodSubmitSuccess(AuthManageDetailActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {

                                // TODO: 2023-08-12 17:06 这里逻辑有争议，是直接杀死页面，还是仍让停留在页面，但是底部按钮不展示 
                                //通知外侧列表刷新
//                                EventAuthMain eventAuthMain = new EventAuthMain();
//                                eventAuthMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_AUTH_MAIN_LIST);
//                                EventBus.getDefault().post(eventAuthMain);
                                //底部的三个按钮隐藏

                                //直接关闭该页面
                                methodBack();

                            }
                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });


    }

    //已确定和客户取得联系
    private void method_authHasContacted_upLoad() {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.carAttestationId, extra_carattestation.getCarAttestationId());//类别：1新车；2二手车

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATECONFIRM_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateConfirm_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateConfirm(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(AuthManageDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        //给个报错提示
                        if (!TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);
                        //先通知详情刷新，再通知外侧上层列表刷新
                        EventAuthDetail eventAuthDetail = new EventAuthDetail();
                        eventAuthDetail.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_AUTH_DETAIL);
                        EventBus.getDefault().post(eventAuthDetail);

                        methodSubmitSuccess(AuthManageDetailActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {
                                EventAuthMain eventAuthMain = new EventAuthMain();
                                eventAuthMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_AUTH_MAIN_LIST);
                                EventBus.getDefault().post(eventAuthMain);
                            }
                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInAuthDetail(EventAuthDetail eventAuthDetail) {

        if (eventAuthDetail != null) {

            if (eventAuthDetail.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_AUTH_DETAIL) {

                //如果发起搜索，要重置 第1页
//                pagination_upLoad = Parameterkey.pageNum_default_first;

                //清空历史数据
                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

                if (authManageDetailAdapter != null) {
                    authManageDetailAdapter.notifyDataSetChanged();
                }

                getServerDatas();

            }

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (popupViewConfirm != null) {
            if (popupViewConfirm.isShow()) {
                popupViewConfirm.dismiss();
            }
        }


        if (basePopupView_cancelReason != null) {
            basePopupView_cancelReason.onDestroy();
            basePopupView_cancelReason = null;
        }

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (authManageDetailAdapter != null) {
            authManageDetailAdapter.notifyDataSetChanged();
            authManageDetailAdapter = null;
        }

        // : 2023-07-14 18:01 释放内存
        EventBus.getDefault().unregister(this);

    }

    @Override
    protected void methodBack() {
        ActivityUtils.finishActivity(this);
    }

    @Override
    public void processExtraData() {

        Bundle extras_bundle = this.getIntent().getExtras();

        if (extras_bundle != null) {

            //标志 是从总列表 进来的，还是从 历史记录进来的；
            flag_jumpfrom_where = extras_bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);

            extra_carattestation = extras_bundle.getParcelable(ExtraKey.EXTRA_CARATTESTATION);

        }

    }
}